'use strict';

const db = uniCloud.database();
const collection = db.collection('food-dishes');

exports.main = async (event, context) => {
  const { dishData } = event.data || {};
  
  if (!dishData) {
    return {
      code: 400,
      message: '缺少菜品数据',
      data: null
    };
  }
  
  // 验证必填字段
  if (!dishData.name || dishData.name.trim() === '') {
    return {
      code: 400,
      message: '菜品名称不能为空',
      data: null
    };
  }
  
  if (!dishData.category_id || dishData.category_id.trim() === '') {
    return {
      code: 400,
      message: '菜品分类不能为空',
      data: null
    };
  }
  
  try {
    // 检查菜品名称是否已存在
    const existingDish = await collection.where({
      name: dishData.name.trim()
    }).get();
    
    if (existingDish.data.length > 0) {
      return {
        code: 400,
        message: '菜品名称已存在',
        data: null
      };
    }
    
    // 准备插入数据（不要手动设置 create_date / update_date，交给 schema 默认值）
    const insertData = {
      name: dishData.name.trim(),
      description: dishData.description || '',
      image: dishData.image || '',
      category_id: dishData.category_id,
      ingredients: {
        main_ingredients: (dishData.ingredients && dishData.ingredients.main_ingredients) || '',
        auxiliary_ingredients: (dishData.ingredients && dishData.ingredients.auxiliary_ingredients) || '',
        seasonings: (dishData.ingredients && dishData.ingredients.seasonings) || ''
      },
      spiciness: dishData.spiciness !== undefined ? parseInt(dishData.spiciness) : 0,
      is_recommended: dishData.is_recommended !== undefined ? !!dishData.is_recommended : false
    };
    
    const result = await collection.add(insertData);
    
    return {
      code: 200,
      message: '添加成功',
      data: {
        _id: result.id,
        ...insertData
      }
    };
  } catch (error) {
    return {
      code: 500,
      message: `添加失败: ${error && error.message ? error.message : '未知错误'}`,
      data: null
    };
  }
};